from typing import List
from model_config import MODEL_PROVIDERS

class ModelRegistry:
    """模型注册表，用于管理和获取可用的模型列表"""

    @staticmethod
    def get_all_embed_models() -> List[str]:
        """获取所有可用的embedding模型列表
        
        Returns:
            List[str]: 带provider前缀的模型名称列表，格式为 'provider/model'
            例如: ['ollama/bge-m3:latest', 'openai/text-embedding-3-large']
        """
        models = []
        for provider, config in MODEL_PROVIDERS.items():
            embed_models = config.get('embed_models', [])
            for model in embed_models:
                models.append(f"{provider}/{model}")
        return models

    @staticmethod
    def get_all_llm_models() -> List[str]:
        """获取所有可用的LLM模型列表
        
        Returns:
            List[str]: 带provider前缀的模型名称列表，格式为 'provider/model'
            例如: ['ollama/qwen2.5:3b', 'openai/gpt-3.5-turbo']
        """
        models = []
        for provider, config in MODEL_PROVIDERS.items():
            llm_models = config.get('llm_models', [])
            for model in llm_models:
                models.append(f"{provider}/{model}")
        return models

    @staticmethod
    def split_model_name(full_model_name: str) -> tuple[str, str]:
        """解析完整的模型名称，分离出provider和模型名
        
        Args:
            full_model_name: 完整的模型名称，格式为 'provider/model'
            
        Returns:
            tuple[str, str]: (provider, model_name)
            
        Raises:
            ValueError: 当模型名称格式不正确时
        """
        try:
            provider, model = full_model_name.split('/', 1)
            if provider not in MODEL_PROVIDERS:
                raise ValueError(f"未知的provider: {provider}")
            return provider, model
        except ValueError:
            raise ValueError(f"模型名称格式不正确: {full_model_name}，应为 'provider/model' 格式")

    @staticmethod
    def get_provider_config(provider: str) -> dict:
        """获取指定provider的配置信息
        
        Args:
            provider: provider名称
            
        Returns:
            dict: provider的配置信息
            
        Raises:
            ValueError: 当provider不存在时
        """
        if provider not in MODEL_PROVIDERS:
            raise ValueError(f"未知的provider: {provider}")
        return MODEL_PROVIDERS[provider]

    @classmethod
    def validate_model(cls, full_model_name: str, model_type: str = "llm") -> bool:
        """验证模型是否可用
        
        Args:
            full_model_name: 完整的模型名称，格式为 'provider/model'
            model_type: 模型类型，'llm' 或 'embed'
            
        Returns:
            bool: 模型是否可用
        """
        try:
            provider, model = cls.split_model_name(full_model_name)
            config = cls.get_provider_config(provider)
            model_list = config.get('llm_models' if model_type == 'llm' else 'embed_models', [])
            return model in model_list
        except ValueError:
            return False
